package com.ycwl.freetv.program;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

import com.ycwl.library.ParseUIFromJson;

public final class Video implements ProgramInterface {
    ExoPlayer player;
    PlayerView playerView;

    boolean isPlaying;

    public Video(Context context, ParseUIFromJson.BaseNode baseNode) {
        this.isPlaying = false;
        PlayerView playerView1 = new PlayerView(context);
        ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(960, 540);
        marginLayoutParams.leftMargin = baseNode.x.intValue();
        marginLayoutParams.topMargin = baseNode.y.intValue();
        marginLayoutParams.width = baseNode.width.intValue();
        marginLayoutParams.height = baseNode.height.intValue();
        playerView1.setLayoutParams(marginLayoutParams);
        ExoPlayer exoPlayer = new ExoPlayer.Builder(context).build();
        playerView1.setPlayer(exoPlayer);
        playerView1.setUseController(false);
        this.playerView = playerView1;
        try {
            exoPlayer.addMediaItem(MediaItem.fromUri(baseNode.url));
            exoPlayer.addListener(new Player.Listener() {
                @Override
                public void onIsLoadingChanged(boolean isLoading) {
                    Player.Listener.super.onIsLoadingChanged(isLoading);
                }
            });
        } catch (NullPointerException e) {
            e.printStackTrace();
            Toast.makeText(context.getApplicationContext(), "视频初始化失败" + baseNode.content, Toast.LENGTH_LONG).show();
        }



        this.player = exoPlayer;
    }
    @Override
    public void play() {
        this.player.prepare();
        this.player.setPlayWhenReady(true);
    }

    @Override
    public void stop() {
        player.stop();
        playerView.setPlayer(null);
        playerView.destroyDrawingCache();
        player.release();
    }

    @Override
    public void setTotalTime(int totalTime) {

    }

    @Override
    public void pause() {
        player.pause();
    }

    @Override
    public View getView() {
        return this.playerView;
    }
}
